const checkLogin = require('./checkLogin.js');
const wxHttpHandler = function ({
  type,
  path,
  data,
  fn,
  header
} = {}) {
  var session = wx.getStorageSync('loginFlag')
  var userId = wx.getStorageSync('userId')
  header = header && typeof header === 'object' ? header : {
    session: session,
    userId: userId
  }
  // console.log(header);
  wx.request({
    url: path,
    method: type,
    header: header,
    data: data,
    success: function (res) {
      if (res.data.code === 4) {
        // session 过期
        wx.showLoading({
          title: '正在重新登录',
        })
        checkLogin();
      } else if (res.data.code != 0) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000,
          mask: true
        });
        // toFix : 测试
        fn(res.data);
      } else {
        fn(res.data);
      }
    },
    fail: function () {
      wx.showToast({
        title: '服务端出错!',
        icon: 'error',
        duration: 2000,
        mask: true
      });
    }
  })
}
module.exports = wxHttpHandler;